import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { FarmService } from "../../../../service/farm.service";
import { DataSourceService } from "../../../../service/data-source/data-source.service";
import { Farm } from "../../../../entity/farm.model";
import { User } from "../../../../entity/user.model";
import { SubstationData } from "../../../../entity/substation-data";
import { SubstationFarmData } from "../substation/substation-farm-data";

@Component({
  selector: 'app-substation',
  templateUrl: './substation.component.html',
  styleUrls: ['./substation.component.css']
})
export class SubstationComponent implements OnInit {
  /**风场集合 */
  private farms: Farm[] = [];

  private user: User = new User();

  public substationDataSources: SubstationData[] = [];

  /**
   * 升压站数量
   * 
   * @memberof SubstationComponent
   */
  @Output()
  substationDataTotalChange = new EventEmitter<Number>();

  /**
   * 升压站按风场数据汇总
   * 
   * @type {SubstationFarmData[]}
   * @memberof SubstationComponent
   */
  public substationFarmDatas: SubstationFarmData[] = [];

  constructor(
    private farmService: FarmService,
    private dataSource: DataSourceService,
  ) {
    this.user.userId = 1;
  }

  ngOnInit() {
    this.loadDate()
  }
  ngOnDestroy(): void {
    if (this.dataSource != null)
      this.dataSource.dispose();
  }



  /**加载数据 */
  private loadDate() {
    Promise.all([
      this.farmService.getFarms()])
      .then(res => {
        if (!res) { return false; };
        this.farms = res[0];

        this.substationFarmDatas = [];
        this.farms.forEach((farm, i) => {
          this.substationFarmDatas.push({
            farmId: farm.farmId,
            farmName: farm.farmName,
            substations: [],
            substationNumber: 0,
            isChecked: i == 0 ? true : false,
          })
        })
        this.subscribeSubstation();
      })
      .catch(error => {
        console.log("app-substation has error", error);
      })
  }

  /**订阅升压站数据 */
  private subscribeSubstation() {
    this.dataSource
      .substation(this.user.userId)
      .subscribe(
        next => {
          next = next.filter(o =>o.confirm == false);
          this.substationDataSources.unshift(...next);
          let last = [];//200以后的数据集合
          if (this.substationDataSources.length > 100) {
            last = this.substationDataSources.slice(100)
            this.substationDataSources = this.substationDataSources.slice(0, 100);
          }
          // this.substationDataTotalChange.emit(this.substationDataSources.length);
          this.totalUnConfirmSubstation()
          this.resolving(next, last);
        });
  }

  /**
   * 按风场解析数据
   * substationDatas推送过来的数据集合
   */
  resolving(substationDatas: SubstationData[], last) {

    substationDatas.forEach((data, index) => {
      let farmData = this.substationFarmDatas.filter(d => d.farmId == data.farmId);
      farmData[0].substations.unshift(data);
      // farmData[0].substationNumber = farmData[0].substations.length;
    })

    this.substationFarmDatas.forEach(farmData => {
      last.forEach(ele => {
        farmData.substations.forEach((substation, index) => {
          if (substation == ele) {
            farmData.substations.splice(index, 1);
            index--;
          }
        })
      });
      // farmData.substationNumber = farmData.substations.filter(o =>o.confirm==false).length;
    })

    this.totalUnConfirmSubstation();
  }

  /**
   * 单条报警确认
   */
  onConfirm(data: SubstationData) {
    data.confirm = true;
    this.totalUnConfirmSubstation();
  }
  onAllConfirm() {
    this.substationDataSources.forEach(ele => {
      if (!ele.confirm) {
        ele.confirm = true;
      }
    })
    this.totalUnConfirmSubstation();
  }
  /**
   * 统计未确认数量
   */
  totalUnConfirmSubstation() {

    let temporarys = [];
    temporarys = this.substationDataSources.filter(o => o.confirm == false);
    this.substationDataTotalChange.emit(temporarys.length);

    this.substationFarmDatas.forEach(farmData => {
      farmData.substationNumber = farmData.substations.filter(o => o.confirm == false).length;
    });
  }

}






// WEBPACK FOOTER //
// ./src/app/module/navigation/alarm-lamp/substation/substation.component.ts